#include "../../Base/StdAfx.h"
#include "IniReader.h"
#include "IniSection.h"
#include "../../Base/StringUtil.h"

IniReader::IniReader(const tstring& filename):m_Filename(filename),m_pIniFile(0)
{
	m_Input.open(filename.c_str());
	Read();
}

IniReader::~IniReader(void)
{
	if(m_pIniFile != 0) delete m_pIniFile;
}

bool IniReader::Read(){
	if ( !m_Input)
		return false;
	tstring line;
	IniSection* currentSection=NULL;
	m_pIniFile = new IniFile();
	if (m_Input.is_open())
	{
		while (! m_Input.eof() )
		{
			getline (m_Input,line);
			if ( line.find(_T("["),0) != string::npos ){
				// create an inisection and add it to the map
				size_t begin = line.find(_T('['),0)+1;
				size_t end = line.find(_T(']'),0)-1;
				tstring sectionName = line.substr(begin,end);
				sectionName = StringUtil::TrimWhiteSpace(sectionName);
				currentSection = new IniSection(sectionName);
				m_pIniFile->AddIniSection(currentSection);
			}
			else
			{
				if ( line.find(_T("="),0) != string::npos){
					StringUtil::Split(line,_T("="),m_ParseHelp);
					if ( currentSection != NULL)
					{
						tstring key = StringUtil::TrimWhiteSpace(m_ParseHelp[0]);
						tstring value = StringUtil::TrimWhiteSpace(m_ParseHelp[1]);
						currentSection->AddKeyValue(key,value);
					}

				}
			}
		}
	}
	return true;
}